import zipfile, json, os, shutil

"""
Datapack Dir
-data
    -NAMESPACE
        -"functions"
            -FILENAME.mcfunction
        -"recipes"
        -etc
-pack.mcmeta
"""

def zipDir(dirpath):
    
    z = zipfile.ZipFile(dirpath + '.zip', "w")
    
    for path,dirnames,filenames in os.walk(dirpath):
        fpath = path.replace(dirpath,'')
        for filename in filenames:
            z.write(os.path.join(path,filename),os.path.join(fpath,filename))
            
    z.close()

class File:
    def __init__(self, orgName):
        self.name = orgName

    def FillFile(self, father):
        print("Creating file ...")
        shutil.copy(self.name, father + '/' + self.name)

class Component:
    def __init__(self, name):
        self.name = name
        self.files = []

    def FillFiles(self, father):
        dirname = father + "/" + self.name

        print("Creating Component ", dirname)
        if not os.access(dirname, os.F_OK):
            os.mkdir(dirname)
        for file in self.files:
            file.FillFile(dirname)

    def PushFile(self, file):
        self.files.append(file)

class Namespace:
    def __init__(self, name):
        self.name = name
        self.content = []

    def FillFiles(self, father):
        dirname = father + "/" + self.name

        print("Creating namespace ", dirname)
        if not os.access(dirname, os.F_OK):
            os.mkdir(dirname)
        for content in self.content:
            content.FillFiles(dirname)

    def PushComponent(self, content):
        self.content.append(content)

class Datapack:
    def __init__(self, name, desp):
        self.name = name
        self.desp = desp
        self.namespaces = []

    def PushNamespace(self, Namespace):
        self.namespaces.append(Namespace)

    def FillFiles(self):
        dirname = "./" + self.name

        # Create subdirectories

        print("Creating datapack", dirname)
        if not os.access(dirname, os.F_OK):
            os.mkdir(dirname)

        dirname += "/data"
        if not os.access(dirname, os.F_OK):
            os.mkdir(dirname)

        for namespace in self.namespaces:
            namespace.FillFiles(dirname)

        # Write pack.mcmeta
        dirname = "./" + self.name
        with open(dirname + "/pack.mcmeta", "w") as file:
            print(self.GetMcmeta(), file=file)

    def GetMcmeta(self):
        return json.dumps({"pack":{"description": self.desp, "pack_format": 4}})

def GenerateDatapack(Name = "music"):
    ns = Namespace("std")
    cp = Component("functions")
    fl = File("f.mcfunction")
    dp = Datapack(Name, "Auto-generated datapack")
    cp.PushFile(fl)
    ns.PushComponent(cp)
    dp.PushNamespace(ns)
    dp.FillFiles()

    zipDir(dp.name)

    shutil.rmtree(dp.name)

if __name__ == '__main__':
    GenerateDatapack()
    
